import { Component, Input, Output, EventEmitter, AfterViewInit, SimpleChanges, OnChanges } from '@angular/core';
import {ToDoItem} from './interface';
import * as distanceInWordsToNow from 'date-fns/distance_in_words_to_now';

@Component({
  selector: 'todo-tab',
  template: `
    <div *ngIf="data.list?.length === 0; else listTpl" class="not-found">
      <img *ngIf="data.emptyImage" src="{{data.emptyImage}}" alt="not found"/>
      <p class="not-found-title">{{data.emptyText || '无通知'}}</p>
    </div>
    <ng-template #listTpl>

      <div class="todo-genre">
        <div class="todo-genre-title">{{data.title}} ● <span class="text-red">{{data.list.length}}</span></div>
        <div class="todo-genre-search">
          <button apes-button apesType="primary" apesShape="circle" (click)="showSearch()">
            <i apes-icon apesType="search"></i>
          </button>
        </div>
      </div>

      <div [class.todo-search-input]="!isSearch">
        <input apes-input (keyup)="onKeyUp($event)" placeholder="快速查找"/>
      </div>

      <div class="todo-markRead">
        <button apes-button apesType="primary" (click)="markRead(_list)">全部标记已读</button>
      </div>


      <apes-list [apesDataSource]="_list" [apesRenderItem]="item" class="apes-todo-list-main" >
        <ng-template #item let-item>
          <apes-list-item [ngClass]="{'read': item.read}">
            <apes-list-item-meta
              [apesTitle]="apesTitle"
              [apesDescription]="apesDescription"
              apesAvatar="assets/tmp/img/oa/message.png"
              class="{{prefixCls}}-list">
              <!--apesAvatar="https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png">-->
              <ng-template #apesTitle>
                <!--{{item.taskName}} : {{item.taskId}}-->
                <!--<div class="extra" *ngIf="item.extra">-->
                  <!--<apes-tag [apesColor]="item.color">{{item.extra}}</apes-tag>-->
                <!--</div>-->
                <div (click)="onClick(item)">
                  <div class="{{prefixCls}}-list-business" >单号：{{item.businessKey}}</div>
                  <div class="{{prefixCls}}-list-type">{{item.taskName}}</div>
                </div>
              </ng-template>
              <ng-template #apesDescription>
                <!--<div *ngIf="item.content" class="description">{{item.content | json}}</div>-->
                <ul *ngIf="getDataContent(item.content)" class="description" [class.showMore]="!isShowMore">
                  <li *ngFor="let data of contentData" style="line-height: 1.5; max-width: 400px;">{{data}}</li>
                  <!--{{item.content | json}}-->
                </ul>
                <div>
                  <div *ngIf="item.createTime" class="datetime">
                    {{getDateTime(item.createTime)}}
                  </div>
                  <!--<div *ngIf="!isShowMore">-->
                    <!--<button apes-button apesType="default" (click)="showMore($event)">更多</button>-->
                  <!--</div>-->
                </div>
              </ng-template>
            </apes-list-item-meta>
          </apes-list-item>
        </ng-template>
      </apes-list>
    </ng-template>
  `,
  preserveWhitespaces: false,
})
export class TodoTabComponent implements AfterViewInit,OnChanges {
  @Input() data: ToDoItem;
  @Output() select = new EventEmitter<any>();
  @Output() read = new EventEmitter<any>();
  prefixCls = 'apes-todo';
  contentData: any[] = [];
  _list = [];

  isSearch:boolean = false;
  isShowMore:boolean = false;

  constructor() {

  }

  showSearch(){
    if(this.isSearch){
      this.isSearch = false;
    }else{
      this.isSearch = true;
    }
    return this.isSearch;
  }

  // showMore(e){
  //   console.log(e);
  //   return this.isShowMore = true;
  // }

  ngAfterViewInit() {
    /* 用于处理前端告警 */
    setTimeout(()=>{
      this._list = this.data.list;
    },100);
  }

  ngOnChanges(changes: SimpleChanges): void {
    this._list = this.data.list;
  }

  onClick(item: ToDoItem) {
    this.select.emit({
      title: this.data.taskName,
      item,
    });
  }

  markRead(item) {
    this.read.emit(
      item
    )
  }


  showContentData(data: any) {
    this.contentData = [];
    for (let key in  data) {
      this.contentData.push(key + ':' + data[key]);
    }
  }

  onKeyUp(param) {
    let value = param.target.value;
    if (value) {
      this._list = this.data.list.filter( item => {
         return this.filter(item, value);
      });
    } else {
      this._list = this.data.list;
    }
  }

  filter(item, value) {
     if (item.businessKey.indexOf(value) > -1) {
       return true;
     }
    let content = item.content;
    let result = false;
    for (const key in  content) {
      let keyValue = "" + content[key];
      result = keyValue.indexOf(value) > -1;
      if (result === true) {
        return result;
      }
    }
    return false;
  }

  getDataContent(metadata) {
    if (metadata) {
      this.showContentData(metadata);
      return true;
    } else {
      return false;
    }
  }

  getDateTime(datetime) {
    let date = new Date(datetime);
    return distanceInWordsToNow(date, {
      locale: (window as any).__locale__,
    });
  }
}
